package com.thread;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class PrintABCForSync {

    public static void main(String[] args) throws InterruptedException {
        Cycle2 cycle = new Cycle2(15);
        ThreadPoolExecutor executor = new ThreadPoolExecutor(3, 3, 2, TimeUnit.SECONDS, new LinkedBlockingQueue<>());
        executor.submit(()->{
            try {
                cycle.printA();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        executor.submit(()->{
            try {
                cycle.printB();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            });
        executor.submit(()->{
            try {
                cycle.printC();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        executor.shutdown();

    }
}



class Cycle2 {

    int k = 0;
    int count;

    public Cycle2(int count) {
        this.count = count;
    }

    public synchronized void printA() throws InterruptedException {
        for (int i = 0; i < count; i++) {
            while (k != 0) {
                this.wait();
            }

            System.out.println(i + ":" + "A");
            k++;
            this.notifyAll();
        }
    }

    public synchronized void printB() throws InterruptedException {
        for (int i = 0; i < count; i++) {
            while (k != 1) {
                this.wait();
            }

            System.out.println(i + ":" + "B");
            k++;
            this.notifyAll();
        }
    }

    public synchronized void printC() throws InterruptedException {
        for (int i = 0; i < count; i++) {
            while (k != 2) {
                this.wait();
            }

            System.out.println(i + ":" + "C");
            k = 0;
            this.notifyAll();
        }
    }

}
